<template>
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
    <el-form ref="foundationInfoFormRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="100px">
      <h2 class="text-black">基础信息</h2>
      <el-row :gutter="24">
        <el-col v-for="(item, index) in formFields" :key="index" :span="item.span">
          <el-form-item v-if="item.type == 'text'" :label="item.label" :prop="item.prop">
            <el-input v-model="formData.form[item.model]" :placeholder="'请输入' + item.label" />
          </el-form-item>
          <el-form-item v-if="item.type == 'file'" :label="item.label" :prop="item.prop">
            <file-upload v-model="formData.form[item.model]" />
          </el-form-item>
          <el-form-item v-if="item.type == 'image'" :label="item.label" :prop="item.prop">
            <image-upload v-model="formData.form[item.model]" />
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <h2 class="text-black">经营信息</h2>
        <div v-if="formData.parkmanagementInformation == null || formData.parkmanagementInformation.length === 0" style="text-align: right">
          <el-button :loading="buttonLoading" type="primary" @click="handlePush">新增</el-button>
        </div>
        <H2 class="mb-5" style="text-align: center; font-weight: bold">园区经营信息</H2>
        <el-table :data="formData.parkmanagementInformation">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="year" label="年度">
            <template #default="scope">
              <el-date-picker v-model="scope.row.year" style="width: 100px" format="YYYY" value-format="YYYY" type="year" />
            </template>
          </el-table-column>
          <el-table-column prop="deadlineDate" label="截止日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.deadlineDate" style="width: 100%" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column prop="lettingRate" label="出租率(%)">
            <template #default="scope">
              <el-input v-model="scope.row.lettingRate" min="0" max="100" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="accumulatedAmount" label="当年累计租金收入（万元）">
            <template #default="scope">
              <el-input v-model="scope.row.accumulatedAmount" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="outputValue" label="当年产值（万元）">
            <template #default="scope">
              <el-input v-model="scope.row.outputValue" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="disabled">-</div>
              <div v-else>
                <el-button link type="primary" @click="handlePush"> 新增 </el-button>
                <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getFoundationInfo,
  addFoundationInfo,
  updateFoundationInfo,
  addParkmanagementInformation,
  updateParkmanagementInformation,
  getParkmanagementInformationList,
  delParkmanagementInformationList
} from '@/api/zichanguanli/foundationInfo/index';
import { validateNumber, validateInteger } from '@/utils/formRules';
import { getLeaseInformation, addLeaseInformation, updateLeaseInformation } from '@/api/zichanguanli/leaseInformation';
import { fa } from 'element-plus/es/locale/index.mjs';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 表单字段配置
const formFields = [
  { label: '园区名称', prop: 'form.name', model: 'name', type: 'text', span: 6 },
  { label: '位置', prop: 'form.position', model: 'position', type: 'text', span: 6 },
  { label: '面积(亩)', prop: 'form.area', model: 'area', type: 'text', span: 6 },
  { label: '建筑面积', prop: 'form.floorArea', model: 'floorArea', type: 'text', span: 6 },
  { label: '管理单位', prop: 'form.managementUnit', model: 'managementUnit', type: 'text', span: 6 },
  { label: '对接人', prop: 'form.contactPerson', model: 'contactPerson', type: 'text', span: 6 },
  { label: '联系人', prop: 'form.associates', model: 'associates', type: 'text', span: 6 },
  { label: '园区估值', prop: 'form.estimation', model: 'estimation', type: 'text', span: 6 },
  { label: '物业公司', prop: 'form.propertyCompany', model: 'propertyCompany', type: 'text', span: 6 },
  { label: '物业人数', prop: 'form.numberOfProperties', model: 'numberOfProperties', type: 'text', span: 6 },
  { label: '物业联系人', prop: 'form.propertyContacts', model: 'propertyContacts', type: 'text', span: 6 },
  { label: '物业电话', prop: 'form.propertyTelephone', model: 'propertyTelephone', type: 'text', span: 6 },
  { label: '园区备注', prop: 'form.remark', model: 'remark', type: 'text', span: 12 },
  { label: '园区附件', prop: 'form.attachments', model: 'attachments', type: 'file', span: 12 },
  { label: '园区介绍', prop: 'form.introduce', model: 'introduce', type: 'text', span: 24 },
  { label: '实景图片', prop: 'form.images', model: 'images', type: 'image', span: 24 }
];
const formRules = reactive({
  'form.id': [{ required: true, message: '园区主键标识不能为空', trigger: 'blur' }],
  'form.name': [{ required: true, message: '园区名称不能为空', trigger: 'blur' }],
  'form.position': [{ required: true, message: '位置不能为空', trigger: 'blur' }],
  'form.area': [
    { required: true, message: '面积(亩)不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: ['change', 'blur'] }
  ],
  'form.floorArea': [
    { required: true, message: '建筑面积不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: ['change', 'blur'] }
  ],
  'form.managementUnit': [{ required: true, message: '管理单位不能为空', trigger: 'blur' }],
  'form.propertyCompany': [{ required: true, message: '物业公司不能为空', trigger: 'blur' }],
  'form.numberOfProperties': [
    { required: true, message: '物业人数不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: ['change', 'blur'] }
  ],
  'form.propertyContacts': [{ required: true, message: '物业联系人不能为空', trigger: 'blur' }],
  'form.propertyTelephone': [
    { required: true, message: '物业电话不能为空', trigger: 'blur' },
    {
       required: true,
      message: '请填写正确的手机号码',
      trigger: 'blur'
    }
  ],
  'form.introduce': [{ required: true, message: '园区介绍不能为空', trigger: 'blur' }],
  'form.images': [{ required: false, message: '实景图片不能为空', trigger: 'blur' }],
  'form.creatTime': [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
  'form.estimation': [{ validator: validateNumber, trigger: ['change', 'blur'] }]
});

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialog = reactive({
  visible: false,
  title: ''
});
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改

const formData: any = ref({
  form: {
    id: undefined,
    name: undefined,
    position: undefined,
    area: undefined,
    floorArea: undefined,
    managementUnit: undefined,
    contactPerson: undefined,
    associates: undefined,
    estimation: undefined,
    propertyCompany: undefined,
    numberOfProperties: undefined,
    propertyContacts: undefined,
    propertyTelephone: undefined,
    remark: undefined,
    attachments: undefined,
    introduce: undefined,
    images: undefined,
    creatTime: undefined
  },
  parkmanagementInformation: []
});
const foundationInfoFormRef = ref(); // 表单 Ref

const handlePush = () => {
  if (!formData.value.parkmanagementInformation) {
    formData.value.parkmanagementInformation = [];
  }
  formData.value.parkmanagementInformation.push({
    id: undefined,
    year: undefined,
    deadlineDate: undefined,
    lettingRate: undefined,
    accumulatedAmount: undefined,
    outputValue: undefined
  });
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delParkmanagementInformationList(row.id);
    formData.value.parkmanagementInformation.splice(index, 1);
  } else {
    formData.value.parkmanagementInformation.splice(index, 1);
  }
};

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialog.visible = true;
  formType.value = type;
  disabled.value = false;
  resetForm();
  // 修改时，设置数据
  if (type === 'detail') {
    disabled.value = true;
    dialog.title = '园区基础信息详情';
  }
  if (type === 'update') {
    dialog.title = '编辑园区基础信息';
  }
  if (type === 'create') {
    dialog.title = '新建园区基础信息';
  }
  if (id) {
    formLoading.value = true;
    try {
      const res = await getFoundationInfo(id);
      const datas = res.data;
      formData.value.form = datas.parkFoundationInfoAddBo;
      formData.value.parkmanagementInformation = datas.parkManagementInformationAddBoList;
      formData.value.parkmanagementInformation.forEach((element) => {
        element.year = String(element.year);
      });
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      id: undefined,
      name: undefined,
      position: undefined,
      area: undefined,
      floorArea: undefined,
      managementUnit: undefined,
      contactPerson: undefined,
      associates: undefined,
      estimation: undefined,
      propertyCompany: undefined,
      numberOfProperties: undefined,
      propertyContacts: undefined,
      propertyTelephone: undefined,
      remark: undefined,
      attachments: undefined,
      introduce: undefined,
      images: undefined,
      creatTime: undefined
    },
    parkmanagementInformation: []
  };
  foundationInfoFormRef.value?.resetFields();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await foundationInfoFormRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      type = 'create';
      const datas = {
        parkFoundationInfoAddBo: formData.value.form,
        parkManagementInformationAddBoList: formData.value.parkmanagementInformation
      };
      await addFoundationInfo(datas);
    } else {
      type = 'update';
      const datas = {
        parkFoundationInfoAddBo: formData.value.form,
        parkManagementInformationAddBoList: formData.value.parkmanagementInformation
      };
      await updateFoundationInfo(datas);
    }
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};
</script>
